package wiki.hitime.stl.daq.web.interceptor;

import wiki.hitime.stl.daq.util.UserContextUtil;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangdaoping
 * @create 2018/1/27 下午3:53
 */
@Component
public class HandlerAccessInterceptor implements HandlerInterceptor {

    private final static String API_PATH_PREFIX = "/api/";
    private final static String MANAGER_API_PATH_PREFIX = "/manager/";


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 增加允许跨域的返回信息
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, vkey, Accept,X-Requested-With,x-di");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        String method = httpServletRequest.getMethod();
        if (HttpMethod.OPTIONS.name().equals(method)) {
            httpServletResponse.setStatus(200);
            return true;
        }

        // 内部接口调用不进行验证[/api/]
        if (httpServletRequest.getRequestURI().startsWith(API_PATH_PREFIX)) {
            return true;
        }

        // 内网管理系统验证[/web/]
        if (httpServletRequest.getRequestURI().startsWith(MANAGER_API_PATH_PREFIX)) {
            if (!UserContextUtil.setUser(httpServletRequest.getHeader("vkey"))) {
                httpServletResponse.sendError(403);
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        UserContextUtil.remove();
    }


}
